﻿using System;
using System.Linq;
using System.Text;
using System.Data.Common;
using System.Linq.Expressions;
using System.Collections.Generic;
using System.Threading.Tasks;
using YiSha.Util;
using YiSha.Util.Extension;
using YiSha.Util.Model;
using YiSha.Data;
using YiSha.Data.Repository;
using YiSha.Entity.QixingManage;
using YiSha.Model.Param.QixingManage;
using Newtonsoft.Json.Linq;
using System.Text.Json;

namespace YiSha.Service.QixingManage
{
    /// <summary>
    /// 创 建：admin
    /// 日 期：2023-03-19 19:40
    /// 描 述：商品信息表服务类
    /// </summary>
    public class GoodsService :  RepositoryFactory
    {
        #region 获取数据
        public async Task<List<GoodsEntity>> GetList(GoodsListParam param)
        {
            var expression = ListFilter(param);
            var list = await this.BaseRepository().FindList(expression);
            return list.ToList();
        }

        public async Task<List<GoodsEntity>> GetPageList(GoodsListParam param, Pagination pagination)
        {
            StringBuilder strSql = new StringBuilder();
            var parameter = new List<DbParameter>();
            strSql.Append(@"SELECT a.* FROM goods_info  a JOIN
            shop_info b ON a.shop_id=b.Id");

            if (param.shopid.IsNullOrZero())
            {
                if (!param.shopname.IsEmpty())
                {
                    strSql.Append(" AND b.shop_name like @shop_name ");
                    parameter.Add(DbParameterExtension.CreateDbParameter("@shop_name", '%' + param.shopname + '%'));
                }
            }
            else
            {
                strSql.Append(" AND a.shop_id=@shop_id ");
                parameter.Add(DbParameterExtension.CreateDbParameter("@shop_id",param.shopid));
            }
            if (!param.goodsname.IsEmpty())
            {
                strSql.Append(" AND a.goods_name like @goodsname ");
                parameter.Add(DbParameterExtension.CreateDbParameter("@goodsname", '%' + param.goodsname + '%'));
            }

            if (!param.tenant_id.IsNullOrZero())
            {
                strSql.Append(" AND a.tenant_id=@tenant_id ");
                parameter.Add(DbParameterExtension.CreateDbParameter("@tenant_id", param.tenant_id));
            }

            if (!param.goods_type.IsNullOrZero() && !param.goods_type.Equals(-1))
            {
                strSql.Append(" AND a.goods_type=@goods_type ");
                parameter.Add(DbParameterExtension.CreateDbParameter("@goods_type", param.goods_type));
            }

            IEnumerable<GoodsEntity> list = await this.BaseRepository().FindList<GoodsEntity>(strSql.ToString(), parameter.ToArray(), pagination);
            //await SetTableDetail(list);
            return list.ToList();
            //var expression = ListFilter(param);
            //var list= await this.BaseRepository().FindList(expression, pagination);
            //return list.ToList();
        }

        
        public GoodsFormDto GetNewFormJson(long id)
        {
                var goods =this.BaseRepository().IQueryable<GoodsEntity>(t => t.Id.Equals(id)).Select(t=>new GoodsFormDto() {
                Id = t.Id,
                price = t.price,
                Type=t.Type,
                is_master = t.is_master,
                shop_id = t.shop_id,
                shop_name = t.shop_name,
                goods_brief = t.goods_brief,
                goods_image = t.goods_image,
                goods_images = t.goods_images,
                goods_intro = t.goods_intro,
                goods_name = t.goods_name,
                goods_core = t.goods_core,
                goods_type = t.goods_type,
                tenant_id = t.tenant_id,
                BaseGoodsAttrList = t.goods_attr,
                input_models=t.modellist,
                goods_images_ext=t.goods_images_ext,
                car_rental_price = t.car_rental_price,
                discount=t.discount,
                unit=t.unit,
                brand_id=t.brand_id
                }).FirstOrDefault();

            if (goods!=null)
            {
                var attr = this.BaseRepository().FindList<GoodsAttrEntity>(t=>t.goods_id==goods.Id).Result.Select(t=>new GoodsGG() { 
                    Id = t.Id,
                    color=t.attr_name,
                    image=t.attr_values,
                    num=t.count,
                    price=t.price,
                    isDefault = t.isDefault
                }).ToList();
                goods.GetList = attr;

                var skupics = this.BaseRepository().FindList<ColorsEntity>(t => t.goods_id == goods.Id).Result.ToList();
                goods.colorsEntities = skupics;

                var sku = this.BaseRepository().FindList<GoodsSkuStockEntity>(t => t.goods_id == goods.Id).Result.ToList();
                goods.goodsSkus = sku;

                var members = this.BaseRepository().FindList<GoodsMemberGradeEntity>(t => t.goodsId == goods.Id).Result.ToList();
                goods.MemberGrade = members;
            }
            return goods;
        }

        public async Task<GoodsEntity> GetEntity(long id)
        {
            var goods = await this.BaseRepository().FindEntity<GoodsEntity>(id);

            //var brand = this.BaseRepository().FindEntity<BrandInfoEntity>(goods.brand_id.Value).Result;

            //goods.brand_name = brand.brand_name;

            return goods;
        }

        public async Task<int> GetMaxSort(long shopid)
        {
            object result = await this.BaseRepository().FindObject(string.Format(@"SELECT MAX(sort) FROM goods_info where shop_id={0}", shopid));
            int sort = result.ParseToInt();
            sort++;
            return sort;
        }
        #endregion

        #region 提交数据
        public async Task NewSaveFormJson(GoodsFormDto entity)
        {
            var db = await this.BaseRepository().BeginTrans();
            try
            {
                //通过店铺id获取会员
                //if (!entity.shop_id.IsNullOrZero()) {
                //    var shop = db.FindEntity<ShopEntity>(entity.shop_id.Value).Result;
                //    if (shop != null)
                //    {
                //        entity.tenant_id = shop.tenant_id;//添加到那个门店就是那个会员信息
                //    }
                //}添加到那个门店就是那个会员信息
                

                GoodsEntity goods = new GoodsEntity();

                goods.price = entity.price;

                goods.is_master = entity.is_master;

                goods.shop_id = entity.shop_id;

                goods.brand_id = entity.brand_id;

                goods.shop_name = entity.shop_name;

                goods.goods_brief = entity.goods_brief;

                goods.goods_image = entity.goods_image;

                goods.goods_images = entity.goods_images;

                goods.goods_intro = entity.goods_intro;

                goods.goods_name = entity.goods_name;

                goods.goods_core = entity.goods_core;

                goods.goods_type = entity.goods_type;

                goods.tenant_id = entity.tenant_id;

                goods.publish_status = 1;

                goods.audit_status = 1;

                goods.Type = entity.Type;

                goods.goods_attr = entity.BaseGoodsAttrList;

                goods.car_rental_price = entity.car_rental_price;

                goods.source = 2;

                goods.goods_images_ext = entity.goods_images_ext;

                goods.modellist = entity.input_models;

                goods.unit = entity.unit;

                goods.modified_time = DateTime.Now;

                goods.discount = entity.discount;

                goods.category_id = entity.category_id;

                goods.category_name = entity.category_name;

                if (!goods.brand_id.IsNullOrZero())
                {
                    var goodsbrand = this.BaseRepository().FindList<BrandInfoEntity>(t => t.Id.Equals(goods.brand_id)).Result.First();
                    if (goodsbrand != null)
                    {
                        goods.brand_name = goodsbrand.brand_name;
                        goods.brand_id = goodsbrand.Id;
                    }
                }
                

                if (goods.goods_type<4) {
                    //根据参数json 读取型号数据
                    //JObject jsonObj = JObject.Parse(goods.goods_attr);

                    //// 检查 "型号" 字段是否存在
                    //JArray xinghaoArray;
                    //if (jsonObj.TryGetValue("型号", out JToken xinghaoToken) && xinghaoToken is JArray)
                    //{
                    //    xinghaoArray = (JArray)xinghaoToken;

                    //    if (xinghaoArray.Count>0)
                    //    {
                    //        var xinghao= xinghaoArray[0].ToString();
                    //        //根据型号名称去查询对应的型号数据
                    //        var goodsmodel =this.BaseRepository().FindList<ModelsEntity>(t=>t.model_name.Equals(xinghao)).Result.First();

                    //        if (goodsmodel!=null) 
                    //        {
                    //            goods.goods_model_id = goodsmodel.Id;
                    //            goods.goods_model = goodsmodel.model_name;
                    //        }
                    //    }
                    //}

                    //if (jsonObj.TryGetValue("品牌", out JToken xinghaoToken1) && xinghaoToken1 is JArray)
                    //{
                    //    xinghaoArray = (JArray)xinghaoToken1;

                    //    if (xinghaoArray.Count > 0)
                    //    {
                    //        var xinghao = xinghaoArray[0].ToString();
                    //        //根据型号名称去查询对应的型号数据
                    //        var goodsbrand = this.BaseRepository().FindList<BrandInfoEntity>(t => t.brand_name.Equals(xinghao)).Result.First();

                    //        if (goodsbrand != null)
                    //        {
                    //            goods.brand_name = goodsbrand.brand_name;
                    //            goods.brand_id = goodsbrand.Id;
                    //        }
                    //    }
                    //}
                }

                List<KeyValue> kvPairs = new List<KeyValue>();

                if (entity.Id.IsNullOrZero())
                {
                    goods.Create();

                    goods.indatetime = DateTime.Now;

                    await db.Insert(goods);

                    foreach (var item in entity.GetList)
                    {
                        GoodsAttrEntity goodsAttr = new GoodsAttrEntity();
                        goodsAttr.attr_values = item.image;
                        goodsAttr.attr_name = item.color;
                        goodsAttr.is_del = 0;
                        goodsAttr.Create();
                        goodsAttr.count = item.num;
                        goodsAttr.price=item.price;
                        goodsAttr.isDefault = item.isDefault;
                        goodsAttr.goods_id = goods.Id;
                        goodsAttr.BaseModifyTime = DateTime.Now;
                        await db.Insert(goodsAttr);
                    }

                    //List<KeyValue> kvPairs = new List<KeyValue>();

                    //清空属性封面
                    //var colorsitems = db.FindList<ColorsEntity>(t => t.goods_id == goods.Id).Result;

                    var colorsitems = db.FindList<ColorsEntity>(t => t.goods_id.Equals(goods.Id)).Result.ToList();

                    if (colorsitems.Count() > 0)
                    {
                        await db.Delete<ColorsEntity>(t => colorsitems.Select(s => s.Id).Contains(t.Id));
                    }

                    foreach (var item in entity.colorsEntities)
                    {
                        //查询分类Type
                        var kvitem = db.FindList<GoodsAttributesEntity>(t => t.goods_types_id == entity.Type && t.attribute_name.Equals(item.key)).Result.FirstOrDefault();

                        if (kvitem != null)
                        {
                            item.attributeval_id = kvitem.Id;

                            item.attributeval_name = kvitem.attribute_name;

                            item.goods_id = goods.Id;

                            item.Create();

                            await db.Insert(item);
                        }
                    }

                    foreach (var item in entity.goodsSkus)
                    {
                        // 反序列化为对象列表
                        List<KeyValue> keyValuePairs = JsonSerializer.Deserialize<List<KeyValue>>(item.sp_data);

                        GoodsSkuStockEntity goodsSku = new GoodsSkuStockEntity();
                        goodsSku.sku_code = item.sku_code;
                        goodsSku.sku_name = item.sku_name;
                        goodsSku.Create();
                        goodsSku.stock = item.stock;
                        goodsSku.price = item.price;
                        goodsSku.isDefault = item.isDefault;
                        goodsSku.goods_id = goods.Id;
                        goodsSku.sp_data = item.sp_data;
                        //goodsSku.pic= item.pic;
                        // attrimage = entity.colorsEntities.Where(t => keyValuePairs.Select(s => t.key).Contains(t.key) && keyValuePairs.Select(s => t.value).Contains(t.value)).FirstOrDefault();
                        var attrimage = entity.colorsEntities.Where(t => keyValuePairs.Select(s => s.Key).Contains(t.key) && keyValuePairs.Select(s => s.Value).Contains(t.value)).FirstOrDefault();

                        if (attrimage != null)
                        {
                            goodsSku.pic = attrimage.pic;
                            goodsSku.colorsid = attrimage.Id;
                        }
                        if (item.Id.IsNullOrZero())
                        {
                            goodsSku.Create();
                            await db.Insert(goodsSku);
                        }

                        foreach (var kv in keyValuePairs)
                        {
                            var kvitem = kvPairs.Where(t => t.Key == kv.Key).FirstOrDefault();

                            var image = entity.colorsEntities.Where(t => t.key == kv.Key).FirstOrDefault();

                            if (image == null)
                            {
                                kv.Description = "1";
                            }
                            else
                            {
                                kv.Description = "0";
                            }

                            if (kvitem == null)
                            {
                                KeyValue keyValue = new KeyValue();
                                keyValue.Key = kv.Key;
                                keyValue.Value = kv.Value;
                                keyValue.Description=kv.Description;
                                kvPairs.Add(keyValue);
                            }
                            else
                            {
                                var kvitemup = kvPairs.Where(t => t.Key == kv.Key && t.Value.Contains(kv.Value)).FirstOrDefault();
                                if (kvitemup == null)
                                {
                                    kvitem.Value = kvitem.Value + "," + kv.Value;
                                }
                            }
                        }
                    }
                }
                else
                {
                    goods.Id = entity.Id;

                    await db.Update(goods);

                    foreach (var item in entity.GetList)
                    {
                        GoodsAttrEntity goodsAttr = new GoodsAttrEntity();
                        goodsAttr.attr_values = item.image;
                        goodsAttr.attr_name = item.color;
                        goodsAttr.is_del = 0;
                        goodsAttr.count = item.num;
                        goodsAttr.goods_id = goods.Id;
                        goodsAttr.price = item.price;
                        goodsAttr.isDefault = item.isDefault;
                        goodsAttr.BaseModifyTime = DateTime.Now;
                        if (item.Id.IsNullOrZero())
                        {
                            goodsAttr.Create();
                            await db.Insert(goodsAttr);
                        }
                        else
                        {
                            goodsAttr.Id = item.Id;
                            await db.Update(goodsAttr);
                        }
                    }

                    var skuinfo=entity.goodsSkus.FirstOrDefault();

                    if (skuinfo!=null && skuinfo.Id.IsNullOrZero())
                    {
                        //防止重置,导致id消失，所有库存全部清空
                        var kvitem = db.FindList<GoodsSkuStockEntity>(t => t.goods_id == goods.Id).Result;
                        if (kvitem.Count()>0)
                        {
                            await db.Delete<GoodsSkuStockEntity>(t => kvitem.Select(s => s.Id).Contains(t.Id));
                        }
                    }

                    //清空属性封面
                    //var colorsitems = db.FindList<ColorsEntity>(t => t.goods_id == goods.Id).Result;
                    //if (colorsitems.Count() > 0)
                    //{
                    //    await db.Delete<ColorsEntity>(t=> colorsitems.Select(s=>s.Id).Contains(t.Id));
                    //}
                    foreach (var item in entity.colorsEntities)
                    {
                        if (item.Id.IsNullOrZero())
                        {
                            //查询分类Type
                            var kvitem = db.FindList<GoodsAttributesEntity>(t => t.goods_types_id == entity.Type && t.attribute_name.Equals(item.key)).Result.FirstOrDefault();

                            if (kvitem != null)
                            {
                                item.attributeval_id = kvitem.Id;

                                item.attributeval_name = kvitem.attribute_name;

                                item.goods_id = goods.Id;

                                item.Create();

                                await db.Insert(item);
                            }
                        }
                        else
                        {
                            await db.Update(item);
                        }
                    }

                    //foreach (var item in entity.colorsEntities)
                    //{
                    //    //查询分类Type
                    //    var kvitem = db.FindList<GoodsAttributesEntity>(t => t.goods_types_id == entity.Type && t.attribute_name.Equals(item.key)).Result.FirstOrDefault();

                    //    if (kvitem != null)
                    //    {
                    //        item.attributeval_id = kvitem.Id;

                    //        item.attributeval_name = kvitem.attribute_name;

                    //        item.goods_id = goods.Id;

                    //        item.Create();

                    //        await db.Insert(item);
                    //    }
                    //}

                    foreach (var item in entity.goodsSkus)
                    {
                        // 反序列化为对象列表
                        List<KeyValue> keyValuePairs = JsonSerializer.Deserialize<List<KeyValue>>(item.sp_data);

                        GoodsSkuStockEntity goodsSku = new GoodsSkuStockEntity();
                        goodsSku.sku_code = item.sku_code;
                        goodsSku.sku_name = item.sku_name;
                        goodsSku.Create();
                        goodsSku.stock = item.stock;
                        goodsSku.price = item.price;
                        goodsSku.isDefault = item.isDefault;
                        goodsSku.goods_id = goods.Id;
                        goodsSku.sp_data = item.sp_data;

                        var attrimage = entity.colorsEntities.Where(t => keyValuePairs.Select(s=>s.Key).Contains(t.key) && keyValuePairs.Select(s => s.Value).Contains(t.value)).FirstOrDefault();

                        if (attrimage != null)
                        {
                            goodsSku.pic = attrimage.pic;
                            goodsSku.colorsid = attrimage.Id;
                        }

                        if (item.Id.IsNullOrZero())
                        {
                            
                            goodsSku.Create();
                            await db.Insert(goodsSku);
                        }
                        else
                        {
                            goodsSku.Id = item.Id;
                            await db.Update(goodsSku);
                        }

                        foreach (var kv in keyValuePairs)
                        {
                            var kvitem=kvPairs.Where(t => t.Key == kv.Key).FirstOrDefault();

                            var image = entity.colorsEntities.Where(t => t.key==kv.Key).FirstOrDefault();

                            if (image == null)
                            {
                                kv.Description = "1";
                            }
                            else
                            {
                                kv.Description = "0";
                            }
                            

                            if (kvitem == null)
                            {
                                kvPairs.Add(kv);
                            }
                            else
                            {
                                var kvitemup = kvPairs.Where(t => t.Key == kv.Key && t.Value.Contains(kv.Value)).FirstOrDefault();
                                if (kvitemup == null)
                                {
                                    kvitem.Value = kvitem.Value + "," + kv.Value;
                                }
                            }
                        }
                    }
                }

                foreach (var item in kvPairs)
                {
                    GoodsAttributeValueEntity valueEntity = new GoodsAttributeValueEntity();
                    valueEntity.value = item.Value;
                    valueEntity.goods_id = goods.Id;
                    //查询分类Type
                    var kvitem = db.FindList<GoodsAttributesEntity>(t => t.goods_types_id == entity.Type && t.attribute_name.Equals(item.Key)).Result.FirstOrDefault();

                    if (kvitem != null)
                    {
                        valueEntity.attribute_id = kvitem.Id;

                        var upkvitem = db.FindList<GoodsAttributeValueEntity>(t => t.attribute_id == kvitem.Id && t.goods_id == entity.Id).Result.FirstOrDefault();

                        if (upkvitem != null)
                        {
                            upkvitem.attribute_name = kvitem.attribute_name;
                            upkvitem.value = item.Value;
                            upkvitem.search_type = item.Description;
                            await db.Update(upkvitem);
                        }
                        else
                        {
                            valueEntity.attribute_name = kvitem.attribute_name;
                            valueEntity.search_type = item.Description;
                            valueEntity.Create();
                            await db.Insert(valueEntity);
                        }
                    }
                }

               

                //重新绑定
                var grcm = this.BaseRepository().FindList<GoodsRentCategoryModels>(t => t.goods_id.Equals(goods.Id)).Result.ToList();

                if (grcm.Count>0) {
                    await db.Delete<GoodsRentCategoryModels>(t => grcm.Select(s => s.Id).Contains(t.Id));
                }

                //绑定租车关系
                if (goods.goods_type.Equals(1))
                {
                    GoodsRentCategoryModels goodsRentCategoryModels = new GoodsRentCategoryModels();
                    goodsRentCategoryModels.goods_id = goods.Id.Value;
                    goodsRentCategoryModels.rentCategoryid = goods.category_id.Value;
                    goodsRentCategoryModels.rentModelsid = goods.goods_model_id.Value;
                    goodsRentCategoryModels.brandid = goods.brand_id;
                    goodsRentCategoryModels.Create();
                    await db.Insert(goodsRentCategoryModels);
                }

                //绑定会员比例
                if (entity.MemberGrade.Count>0)
                {
                    foreach (var item in entity.MemberGrade)
                    {
                        if (item.Id.IsNullOrZero())
                        {
                            item.goodsId = goods.Id;
                            item.Create();
                            await db.Insert(item);
                        }
                        else
                        {
                            await db.Update(item);
                        }
                    }
                }

                await db.CommitTrans();
            }
            catch (Exception ex)
            {
                await db.RollbackTrans();
            }
        }
        public async Task SaveForm(GoodsEntity entity)
        {
            //通过店铺id获取会员
            var shop = this.BaseRepository().FindEntity<ShopEntity>(entity.shop_id.Value).Result;
            if (shop != null)
            {
                entity.tenant_id = shop.tenant_id;//添加到那个门店就是那个会员信息
            }
            
            if (entity.Id.IsNullOrZero())
            {
                entity.goods_core = shop.Id + "_" + entity.goods_core;
                entity.sort = GetMaxSort(entity.shop_id.Value).Result;
                entity.Create();
                entity.indatetime = DateTime.Now;
                await this.BaseRepository().Insert(entity);
            }
            else
            {
                entity.modified_time=DateTime.Now;
                await this.BaseRepository().Update(entity);
            }

            //读取货物并更新货物
            var hws=this.BaseRepository().IQueryable<GoodsWarehouseEntity>(t => t.goods_id == entity.Id).ToList();

            foreach (var item in hws)
            {
                item.goods_model_name = entity.goods_model;
                item.goods_model_id = entity.goods_model_id;
                item.category_id = entity.category_id;
                item.category_name = entity.category_name;
                await this.BaseRepository().Update(item);
            }
        }

        public async Task DeleteForm(string ids)
        {
            long[] idArr = TextHelper.SplitToArray<long>(ids, ',');
            await this.BaseRepository().Delete<GoodsEntity>(idArr);
        }
        #endregion

        #region 私有方法
        private Expression<Func<GoodsEntity, bool>> ListFilter(GoodsListParam param)
        {
            var expression = LinqExtensions.True<GoodsEntity>();
            if (param != null)
            {
                if (!param.id.IsNullOrZero())
                {
                    expression = expression.And(t => t.Id == param.id);
                }
                if (!param.tenant_id.IsNullOrZero())
                {
                    expression = expression.And(t => t.tenant_id == param.tenant_id);
                }
                if (!param.shopid.IsNullOrZero())
                {
                    expression = expression.And(t => t.shop_id == param.shopid);
                }
                if (!param.goods_type.IsNullOrZero() && !param.goods_type.Equals(-1))
                {
                    expression = expression.And(t => t.goods_type == param.goods_type);
                }
            }
            return expression;
        }
        #endregion
    }
}
